import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, removeUserId } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
// 引入用户是否有系统访问权限接口
import {
  getSjcjAuthApi,
  getFwjgAuthApi,
  getRkpcAuthApi,
} from "@/api/user";

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: [],

      // 用户信息
      userId: "", //80cd530287e54c6788925adf2dfc9da1
      userName: "", //测试-赵帅-1
      userCode: "",
      birthday: '',
      sex: "1",
      email: "",
      mobilePhone: "", //15201572964
      // 行政区划
      provinceId: "", //5fba31cfd5fc40c5ac89e4089dd99b08
      cityId: '',
      countyId: '',
      // 部门信息
      deptLevel: "0",
      depts: null,
      orgId: "", //2f655e3a6b75424dae18c5ab57ed1360
      orgName: "", //中国地震灾害防御中心

      showSjcj: false, // 是否有房屋设施数据采集系统访问权限
      showFwjg: false, // 是否有房屋加固改造信息服务、房屋设施数据质检系统访问权限
      showRkpc: false, // 是否有人口普查系统访问权限
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            setToken(res.token)
            this.token = res.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo(userId) {
        return new Promise((resolve, reject) => {
          getInfo(userId).then(res => {
            const user = res.user;
            // 用户基础信息
            if (user) {
              this.userId = user.userId;
              this.name = user.userName;
              this.userName = user.userName;
              this.userCode = user.loginName || user.userCode;
              this.birthday = user.birthday;
              this.sex = user.sex;
              this.email = user.email;
              this.mobilePhone = user.mobilePhone;
              // 行政区划
              this.provinceId = user.provinceId;
              this.cityId = user.cityId;
              this.countyId = user.countyId;
              // 部门信息
              this.deptLevel = user.deptLevel;
              this.depts = user.depts;
              this.orgId = user.orgId;
              this.orgName = user.orgName;
              localStorage.setItem("userName", user.userName);
              localStorage.setItem("orgName", user.orgName || user.extend10);
            }
            // 头像
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
            this.avatar = avatar;
            // 角色和权限
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.setRoutes = ['ROLE_DEFAULT'];
            }
            this.roles.push(user.userName);

            // 获取用户是否有系统访问权限
            this.getSjcjAuth();
            this.getFwjgAuth();
            this.getRkpcAuth();

            resolve(res.user);
          }).catch(error => {
            reject(error);
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(res => {
            this.token = '';
            this.roles = [];
            this.permissions = [];
            removeToken();
            removeUserId();
            localStorage.removeItem("userName");
            localStorage.removeItem("orgName");
            resolve(res);
          }).catch(error => {
            reject(error);
          })
        })
      },
      // 获取用户是否有房屋设施数据采集系统访问权限
      getSjcjAuth() {
        return getSjcjAuthApi({
          userCode: this.userCode,
        }).then(res => {
          const { code, data, message } = res;
          if(code == 200 && data) {
            this.showSjcj = true;
          } else {
            this.showSjcj = false;
          }
        }).catch(err => {
          console.log("获取房屋设施数据采集系统访问权限失败！");
        })
      },
      // 获取用户是否有房屋加固改造信息服务、房屋设施数据质检系统访问权限
      getFwjgAuth() {
        return getFwjgAuthApi({
          userCode: this.userCode,
        }).then(res => {
          const { code, data, message } = res;
          if(code == 200 && data) {
            this.showFwjg = true;
          } else {
            this.showFwjg = false;
          }
        }).catch(err => {
          console.log("获取用户是否有房屋加固改造信息服务、房屋设施数据质检系统访问权限失败！");
        })
      },
      // 获取用户是否有人口普查系统访问权限
      getRkpcAuth() {
        return getRkpcAuthApi({
          userCode: this.userCode,
        }).then(res => {
          const { code, data, message } = res;
          if(code == 200 && data) {
            this.showRkpc = true;
          } else {
            this.showRkpc = false;
          }
        }).catch(err => {
          console.log("获取用户是否有人口普查系统访问权限失败！");
        })
      },
    }
  })

export default useUserStore
